import axios from "axios"
import Vue from 'vue'
import { Message, Loading } from 'element-ui'
import Storage from 'vue-ls'

Vue.use(Storage);

// 创建axios实例
const service = axios.create({
    baseURL: process.env.BASE_API,
    //process.env.BASE_API, // api的base_url
    timeout: 30000  // request timeout
})

// 进行网络请求
service.interceptors.request.use(config => {
config.headers['Cache-Control'] = 'no-cache' // ie清缓存，否则无法正常刷新
config.headers['Pragma'] = 'no-cache' // HTTP/1.1版本，ie清缓存，否则无法正常刷新
    if (config.formType && config.formType === 1){
        config.data = JSON.stringify(config.data)
        config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
        config.transformRequest = [function(data){
            let ret = ''
            for(let it in data){
                ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
            }
            // 返回 ret 从 0 到 ret.length - 1 之间的内容
            return ret.substring(0, ret.length - 1)
        }]

    }
    if(config.showLoading){
        showFullScreenLoading() //开始加载
    }

    if (config.method == 'get') {
        config.params = {
            _t: Date.parse(new Date()) / 1000, // 让每个请求都携带一个不同的时间参数，防止浏览器不发送请求
            ...config.params
        }
    }

    return config
}, error => {
    // 创建错误请求处理
    Promise.reject(error)
})

// 错误的请求处理
const err = (error) => {
    if (error.response){
        switch (error.response.status) {
            case 401:
                console.log({
                    message: '系统提示',
                    description: '未授权, 请重新登录',
                    duration: 4
                })
                break
                case 403:
                console.log({
                  message: '系统提示',
                  description: '拒绝访问'
                })
                break
        
              case 404:
                console.log({
                  message: '系统提示',
                  description: '很抱歉，资源未找到!',
                  duration: 4
                })
                break
              case 500:
                console.log({
                  message: '系统提示',
                  description: 'Token失效，请重新登录!'
                })
                break
              case 504:
                console.log({
                  message: '系统提示',
                  description: '网络超时'
                })
                break
              default:
                console.log({
                  message: '系统提示',
                  description: error.response.data.msg,
                })
                break
        }
    }
    // 返回一个错误请求的处理结果
    return Promise.reject(error)
}

service.interceptors.response.use(response => {
    if (response.config.showLoading){
        tryHideFullScreenLoading()
    }

    // response = response.body
    var res = response.data
    // 修改返回的数据格式
    // res = JSON.parse(res.data)


    // 判断请求结果是否成功 200
    if (res.code === 200){
        return res
    } else {
        Message({
            // 否则返回错误的信息
            message: res.message,
            type: 'error',
            duration: 5 * 1000,
            offset: 100
        })

        // 返回一个实例 
        return Promise.reject(res)
    }
},
error => {
    // 错误处理
    // tryHideFullScreenLoading()  //关闭加载
    Message({
      message: error.msg,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)


// 加载封装
let loading
function startLoading () {
  loading = Loading.service({
    lock: true,
    text: '加载中',
    background: 'rgba(0, 0, 0, 0.7)'
  })
}
// 关闭加载
function endLoading () {
  loading.close()
}
let needLoadingRequestCount = 0
export function showFullScreenLoading () {
  if (needLoadingRequestCount === 0) {
    startLoading()
  }
  needLoadingRequestCount++
}

export function tryHideFullScreenLoading () {
  if (needLoadingRequestCount <= 0) return
  needLoadingRequestCount--
  if (needLoadingRequestCount === 0) {
    endLoading()
  }
}

export default service